package team.dmh.wx.controller;


import io.netty.channel.Channel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import team.dmh.wx.bo.UserBO;
import team.dmh.wx.entity.User;
import team.dmh.wx.exception.ExceptionEnum;
import team.dmh.wx.netty.ChatHandler;
import team.dmh.wx.service.IUserService;
import team.dmh.wx.util.*;
import team.dmh.wx.vo.UserVO;

import javax.validation.Valid;
import java.util.Map;

@Api(tags = "用户操作")
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private FastDFSClient fastDFSClient;


    @ApiOperation("用户退出登录")
    @GetMapping("/logout")
    public Result logout(String id) {
        Channel channel = ChatHandler.users.get(id);
        if (channel != null) {
            channel.close();
            ChatHandler.users.remove(id);
        }
        return ResultUtils.success();
    }

    @ApiOperation("用户登录/注册")
    @PostMapping("/registerOrLogin")
    public Result registerOrLogin(@RequestBody @Valid User user, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            result.getFieldErrors().forEach(e -> stringBuilder.append(e.getDefaultMessage()));
            return ResultUtils.fail(stringBuilder.toString());
        }
        //check if exist
        boolean isExist = userService.queryIsExistByUsername(user.getUsername());
        if (isExist) {
            //login
            User userResult = userService.queryForLogin(user.getUsername(), MD5Utils.encrypt(user.getPassword()));
            if (userResult == null) {
                return ResultUtils.fail(ExceptionEnum.LOGIN_ERROR);
            }
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(userResult, userVO);
            return ResultUtils.success(userVO);
        } else {
            //register
            return ResultUtils.success(userService.register(user));
        }

    }

    @ApiOperation("用户修改个性签名")
    @PostMapping("/setSignature")
    public Result setSignature(@RequestBody Map<String,String> params){
        String userId=params.get("userId");
        String signature=params.get("signature");
        userService.updateById(new User().setId(userId).setSignature(signature));
        User user=userService.getById(userId);
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }

    @ApiOperation("用户注册")
    @PostMapping("/register")
    public Result register(@Valid @RequestBody User user, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            result.getFieldErrors().forEach(e -> stringBuilder.append(e.getDefaultMessage()));
            return ResultUtils.fail(stringBuilder.toString());
        }
        //check if exist
        boolean isExist = userService.queryIsExistByUsername(user.getUsername());
        if (isExist) {
            //error
            return ResultUtils.fail(ExceptionEnum.USER_IS_EXIST);
        } else {
            UserVO userVO = userService.register(user);
            return ResultUtils.success(userVO);
        }
    }

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@Valid @RequestBody User user, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            StringBuilder stringBuilder = new StringBuilder();
            result.getFieldErrors().forEach(e -> stringBuilder.append(e.getDefaultMessage()));
            return ResultUtils.fail(stringBuilder.toString());
        }
        User userResult = userService.queryForLogin(user.getUsername(), MD5Utils.encrypt(user.getPassword()));
        if (userResult == null) {
            return ResultUtils.fail(ExceptionEnum.LOGIN_ERROR);
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userResult, userVO);
        return ResultUtils.success(userVO);
    }

    @ApiOperation("用户上传头像")
    @PostMapping("/uploadImg")
    public Result uploadImg(@ApiParam(name = "userId,imgData", value = "用户id,图片base64数据")
                            @RequestBody UserBO userBO) throws Exception {
        //获取base64字符串转为文件对象
        String imgData = userBO.getImgData();
//        String imgPath = "D:\\img\\face\\" + userBO.getId() + "_img.png";
        String imgPath = "/opt/wx/temp_imgs/" + userBO.getId() + "_img.png";
        MultipartFile img = FileUtils.base64ToMultipartFile(imgPath, imgData);
        String imgUrl = fastDFSClient.uploadImageAndCrtThumbImage(img);
        // 获取缩略图的url a.jpg -> a_80x80.jpg
        String thump = "_80x80.";
        String arr[] = imgUrl.split("\\.");
        String thumpImgUrl = arr[0] + thump + arr[1];
        //保存更新用户信息
        User user = new User().setId(userBO.getId()).setImg(thumpImgUrl).setImgBig(imgUrl);
        userService.updateById(user);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.getById(user.getId()), userVO);
        return ResultUtils.success(userVO);
    }

    @ApiOperation("用户修改个性签名")
    @PostMapping("/getSignature")
    public Result setSignature(@ApiParam(name = "userId,signature", value = "用户id,个性签名")
                               @RequestBody UserBO userBO) {
        String signature = userBO.getSignature();
        String userId = userBO.getId();
        User user = new User().setId(userId).setSignature(signature);
        userService.updateById(user);
        return ResultUtils.success();
    }

    @ApiOperation("用户更改昵称")
    @PostMapping("/setNickname")
    public Result setNickname(@ApiParam(name = "userId,nickname", value = "用户id,昵称") @RequestBody UserBO userBO) {
        userService.updateById(new User().setId(userBO.getId()).setNickname(userBO.getNickname()));
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userService.getById(userBO.getId()), userVO);
        return ResultUtils.success(userVO);
    }


}
